package cn.schoolwow.quickdao.test.module.business.dcl.flow;

import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickdao.domain.database.dcl.DataBaseUser;
import cn.schoolwow.quickdao.domain.database.dcl.GrantOption;
import cn.schoolwow.quickdao.domain.database.parent.DatabaseType;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

public class DCLProcessFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        DatabaseType databaseType = flowContext.checkInstanceData(DatabaseType.class);
        DAO dao = flowContext.checkInstanceData(DAO.class);

        if(DatabaseType.SQLite.equals(databaseType)
                ||DatabaseType.H2.equals(databaseType)
                ||DatabaseType.SQLServer.equals(databaseType)){
            flowContext.broken("当前数据库类型不支持DCL操作!");
        }

        //创建用户
        DataBaseUser dataBaseUser = new DataBaseUser();
        dataBaseUser.username = "dao_control_name";
        dataBaseUser.password = "123456";
        if(dao.hasUserName(dataBaseUser.username)){
            dao.deleteUser(dataBaseUser);
        }

        //数据库授权
        GrantOption grantOption = new GrantOption();
        grantOption.databaseName = "quickdao";
        grantOption.dataBaseUser = dataBaseUser;
        dao.createUserAndGrant(grantOption);

        if(dao.hasUserName("dao_control_name")){
            dao.revoke(grantOption);
            dao.deleteUser(dataBaseUser);
        }
        //创建用户
        dao.createUser(dataBaseUser);
        //授予权限
        dao.grant(grantOption);
        //收回权限
        dao.revoke(grantOption);
        //修改密码
        dao.modifyPassword(dataBaseUser.username, "654321");
        //删除用户
        dao.deleteUser(dataBaseUser);
    }

    @Override
    public String name() {
        return "DCL操作测试流程";
    }
}
